package cn.easybuy.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.easybuy.pojo.Product;
import cn.easybuy.service.ProductService;

@Controller
@RequestMapping("/pro")
public class ProductController {
	
	@Autowired
	ProductService productService;
	private Logger logger = Logger.getLogger(ProductController.class);
	
	private List<Product> list = new ArrayList<Product>();
	private Map<String, Object> map = new HashMap<String, Object>();
	
	/**
	 * 根据分类、页码、页大小查询商品
	 */
	@ResponseBody
	@RequestMapping("/List")
	public Object getProductByPage(@RequestParam(value="epcChildId",required=false)String epcChildId,
									@RequestParam(value="pageIndex",required=false,defaultValue="1")String pageIndex,
									@RequestParam(value="pageSize",required=false,defaultValue="8")String pageSize) {
		try {
			Integer _pageIndex = Integer.parseInt(pageIndex);
			Integer _pageSize = Integer.parseInt(pageSize);
			System.out.println("======================="+epcChildId);
			/* int _epcChildId = epcChildId == null?null:Integer.parseInt(epcChildId); */
			/* System.out.println("========================"+_epcChildId); */
			//productService.getProductList(6, 0, 5);
			_pageIndex = (_pageIndex-1)*_pageSize;
			list = productService.getProductList(epcChildId, _pageIndex, _pageSize);
			int count = productService.getProductCount(epcChildId);
			int totalPage = count%_pageSize==0?count/_pageSize:(count/_pageSize)+1;
			if(list!=null && list.size()>0) {
				map.put("success", true);
				map.put("data", list);
				map.put("count", count);
				map.put("totalPage", totalPage);
				map.put("pageIndex", _pageIndex);
				map.put("message", "获取数据成功");
			}else {
				map.put("success", false);
				map.put("data", null);
				map.put("message", "数据丢失或当前商品信息数据为空");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			map.put("success", false);
			map.put("data", null);
			map.put("message", "服务器出现异常，请联系网站管理员");
			e.printStackTrace();
		}
		return map;
	}
	
	@ResponseBody
	@RequestMapping("/all")
	public Object getProductAll() {
		
		try {
			list = productService.getProductAll();
			if(list!=null && list.size()>0) {
				map.put("success", true);
				map.put("message", "获取数据成功");
				map.put("data", list);
			}else {
				map.put("success", false);
				map.put("message", "数据丢失，获取数据失败");
				map.put("data", null);
			}
		} catch (Exception e) {
			map.put("success", false);
			map.put("message", "服务器出现异常，请联系网站管理员");
			map.put("data", null);
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 获取商品的详情信息
	 * @param epId
	 * @return
	 */
	@RequestMapping("/view")
	@ResponseBody
	public Object getProductView(@RequestParam(value="epId")Integer epId) {
		try {
			Product product = productService.getProductById(epId);
			if(product != null) {
				map.put("success", true);
				map.put("data", product);
				map.put("message", "获取数据成功");
			}else {
				map.put("success", false);
				map.put("data", null);
				map.put("message", "数据丢失，请重新操作");
			}
		} catch (Exception e) {
			map.put("success", false);
			map.put("data", null);
			map.put("message", "服务器出现异常，请联系网站管理员");
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 添加商品信息-----需要商场商品图片
	 * @param product
	 * @param request
	 * @param epFileName
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Object AddSaveInfo(Product product,HttpServletRequest request,@RequestParam(value="attch",required=false)MultipartFile epFileName) {
		String PicPath = null;
		String newFileName = null;
		if(epFileName != null) {
		if(!epFileName.isEmpty()) {
			//设置文件上传路径
			String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"images"+File.separator+"product");
			//获取原文件名
			String oldFileName = epFileName.getOriginalFilename();
			logger.info("====================上传的文件的原文件名"+oldFileName);
			//获取上传的文件的后缀名
			String suffix = FilenameUtils.getExtension(oldFileName);
			logger.info("====================上传文件的后缀名"+suffix);
			//设置最大上传文件的大小
			int fileSize = 500000;
			logger.info("====================上传文件的大小"+epFileName.getSize());
			if(fileSize<epFileName.getSize()) {
				/* request.setAttribute("uploadFileError","上传文件的大小不能超过500k"); */
				map.put("success", false);
				map.put("message", "上传文件的大小不能超过500k");
				map.put("data", null);
				return map;
			}else if(suffix.equalsIgnoreCase("jpg")||suffix.equalsIgnoreCase("jpeg")
					||suffix.equalsIgnoreCase("png")||suffix.equalsIgnoreCase("pneg")) {
				//生成随机文件名
				newFileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_epFileName.jpg";
				File targetFile = new File(path, newFileName);
				if(!targetFile.exists()) {
					targetFile.mkdirs();
				}
				
				try {
					epFileName.transferTo(targetFile);
					PicPath = path +File.separator+ newFileName;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else {
				request.setAttribute("uploadFileError","上传文件的格式有误");
				map.put("success", false);
				map.put("message", "上传文件的格式有误");
				map.put("data", null);
				return map;
			}
		}
		}
		product.setEpFileName(newFileName);
		
		try {
			if(productService.addProduct(product)>0) {
				map.put("success", true);
				map.put("message", "商品信息添加成功");
				map.put("data", product);
				return map;	
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 修改商品信息
	 * @param product
	 * @param request
	 * @param epFileName
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public Object uploadSaveInfo(Product product,HttpServletRequest request,@RequestParam(value="attch",required=false)MultipartFile epFileName) {
		String PicPath = null;
		String newFileName = null;
		//设置文件上传路径
		String path = null;
		//获取商品的旧文件名
		Integer epId = product.getEpId();
		String oldEpFileName = null;
		try {
			Product product2 = productService.getProductById(epId);
			oldEpFileName = product2.getEpFileName();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		if(epFileName != null) {
		if(!epFileName.isEmpty()) {
			//设置文件上传路径
			path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"images"+File.separator+"product");
			//获取原文件名
			String oldFileName = epFileName.getOriginalFilename();
			logger.info("====================上传的文件的原文件名"+oldFileName);
			//获取上传的文件的后缀名
			String suffix = FilenameUtils.getExtension(oldFileName);
			logger.info("====================上传文件的后缀名"+suffix);
			//设置最大上传文件的大小
			int fileSize = 500000;
			logger.info("====================上传文件的大小"+epFileName.getSize());
			if(fileSize<epFileName.getSize()) {
				/* request.setAttribute("uploadFileError","上传文件的大小不能超过500k"); */
				map.put("success", false);
				map.put("message", "上传文件的大小不能超过500k");
				map.put("data", null);
				return map;
			}else if(suffix.equalsIgnoreCase("jpg")||suffix.equalsIgnoreCase("jpeg")
					||suffix.equalsIgnoreCase("png")||suffix.equalsIgnoreCase("pneg")) {
				//生成随机文件名
				newFileName = System.currentTimeMillis()+RandomUtils.nextInt(1000000)+"_epFileName.jpg";
				File targetFile = new File(path, newFileName);
				if(!targetFile.exists()) {
					targetFile.mkdirs();
				}
				
				try {
					epFileName.transferTo(targetFile);
					PicPath = path +File.separator+ newFileName;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else {
				request.setAttribute("uploadFileError","上传文件的格式有误");
				map.put("success", false);
				map.put("message", "上传文件的格式有误");
				map.put("data", null);
				return map;
			}
		}
		}
		product.setEpFileName(newFileName);
		
		try {
			if(productService.updataProduct(product)>0) {
				map.put("success", true);
				map.put("message", "修改商品添加成功");
				map.put("data", product);
				//商品添加完成，删除商品的旧文件
				File file = new File(path, oldEpFileName);
				file.delete();
				return map;	
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 删除商品信息
	 * @param epId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public Object deleteProduct(@RequestParam(value="epId")Integer epId) {
		try {
			if(productService.deleteProduct(epId)>0) {
				map.put("success", true);
				map.put("message", "删除商品信息成功");
			}else {
				map.put("success", false);
				map.put("message", "删除商品信息失败");
			}
		} catch (Exception e) {
			map.put("success", false);
			map.put("message", "服务器出现异常，删除信息失败");
			e.printStackTrace();
		}
		return map;
	}
	
	
}
